package com.yuantong.xyerp.rest.controller;

import com.yuantong.xyerp.core.api.dto.RoleDto;
import com.yuantong.xyerp.core.api.enums.EnumMsgCode;
import com.yuantong.xyerp.core.api.exception.YuantongException;
import com.yuantong.xyerp.core.api.model.Role;
import com.yuantong.xyerp.core.api.model.RoleMenu;
import com.yuantong.xyerp.core.api.model.base.RestResponseModel;
import com.yuantong.xyerp.core.api.service.IRoleMenuService;
import com.yuantong.xyerp.core.api.service.IRoleService;
import com.yuantong.xyerp.rest.controller.base.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by Jianguo.Yin on 2021-07-20.
 */
// @Api(value = "角色控制器")
// @RestController
// @RequestMapping("role")
public class RoleController extends BaseController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IRoleMenuService roleMenuService;



    @ApiOperation(value = "增加角色")
    @Transactional
    @PostMapping("/addRole")
    public RestResponseModel addRole(@RequestBody RoleDto roleDto, HttpServletRequest request) {
        Role role = roleService.findRoleByName(roleDto);
        if (role != null) {
            throw new YuantongException(EnumMsgCode.DATA_ALREADY_EXISTED);
        }
        String roleId = UUID.randomUUID().toString().replaceAll("-","");
        roleDto.setId(roleId);
        roleDto.setCreatorId(this.getSubject(request).getId());
        roleService.addRole(roleDto);

        List<RoleMenu> roleMenus = new ArrayList<>();
        List<String> menuIds = roleDto.getMenuIds();
        for (String menuId :
                menuIds) {
            String roleMenuId = UUID.randomUUID().toString().replaceAll("-","");
            roleMenus.add(new RoleMenu().id(roleMenuId).roleId(roleId).menuId(menuId));
        }
        if (roleMenuService.savePatch(roleMenus)){
            return RestResponseModel.SUCCESS(EnumMsgCode.MSG_SUCCESS);
        }
        throw new YuantongException(EnumMsgCode.DATA_ADD_FAILE);
    }

}
